<template>
  <div class="user-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" @click="showAddUserDialog">新增用户</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-input v-model="searchQuery" placeholder="搜索用户名/手机号" prefix-icon="Search" style="width: 300px; margin-right: 15px;"></el-input>
        <el-select v-model="selectedGroup" placeholder="选择用户分组" style="width: 200px; margin-right: 15px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="提肛运动" value="1"></el-option>
          <el-option label="鼻炎护理" value="2"></el-option>
          <el-option label="综合健康" value="3"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <!-- 用户表格 -->
      <el-table :data="usersData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="用户ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="groupName" label="用户分组" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '活跃' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180"></el-table-column>
        <el-table-column prop="lastLoginAt" label="最后登录" width="180"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showEditUserDialog(scope.row)">编辑</el-button>
            <el-button :type="scope.row.status === 'active' ? 'danger' : 'success'" size="small" @click="handleToggleStatus(scope.row)">
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="userDialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="用户分组" prop="groupId">
          <el-select v-model="userForm.groupId" placeholder="请选择用户分组">
            <el-option label="提肛运动" value="1"></el-option>
            <el-option label="鼻炎护理" value="2"></el-option>
            <el-option label="综合健康" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.status" active-value="active" inactive-value="inactive"></el-switch>
        </el-form-item>
        <template v-if="!editingUserId">
          <el-form-item label="初始密码" prop="password">
            <el-input v-model="userForm.password" type="password" placeholder="请输入初始密码"></el-input>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 搜索和筛选条件
const searchQuery = ref('')
const selectedGroup = ref('')

// 表格数据
const usersData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const multipleSelection = ref([])

// 对话框状态
const userDialogVisible = ref(false)
const editingUserId = ref(null)
const userFormRef = ref()

// 用户表单
const userForm = reactive({
  username: '',
  phone: '',
  email: '',
  groupId: '',
  status: 'active',
  password: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  groupId: [
    { required: true, message: '请选择用户分组', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return editingUserId.value ? '编辑用户' : '新增用户'
})

// 获取用户列表
const fetchUsers = () => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  const mockData = [
    { id: 1, username: '张三', phone: '13800138001', email: 'zhangsan@example.com', groupName: '提肛运动', groupId: '1', status: 'active', createdAt: '2023-07-01 10:00:00', lastLoginAt: '2023-07-25 14:30:00' },
    { id: 2, username: '李四', phone: '13800138002', email: 'lisi@example.com', groupName: '鼻炎护理', groupId: '2', status: 'active', createdAt: '2023-07-02 11:00:00', lastLoginAt: '2023-07-25 13:45:00' },
    { id: 3, username: '王五', phone: '13800138003', email: 'wangwu@example.com', groupName: '综合健康', groupId: '3', status: 'active', createdAt: '2023-07-03 12:00:00', lastLoginAt: '2023-07-24 10:15:00' },
    { id: 4, username: '赵六', phone: '13800138004', email: 'zhaoliu@example.com', groupName: '提肛运动', groupId: '1', status: 'inactive', createdAt: '2023-07-04 13:00:00', lastLoginAt: '2023-07-20 09:30:00' },
    { id: 5, username: '钱七', phone: '13800138005', email: 'qianqi@example.com', groupName: '鼻炎护理', groupId: '2', status: 'active', createdAt: '2023-07-05 14:00:00', lastLoginAt: '2023-07-25 11:20:00' }
  ]
  
  // 应用搜索和筛选
  let filteredData = [...mockData]
  if (searchQuery.value) {
    filteredData = filteredData.filter(user => 
      user.username.includes(searchQuery.value) || 
      user.phone.includes(searchQuery.value)
    )
  }
  if (selectedGroup.value) {
    filteredData = filteredData.filter(user => user.groupId === selectedGroup.value)
  }
  
  total.value = filteredData.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  usersData.value = filteredData.slice(start, end)
}

// 显示新增用户对话框
const showAddUserDialog = () => {
  editingUserId.value = null
  // 重置表单
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  // 重置表单数据
  userForm.username = ''
  userForm.phone = ''
  userForm.email = ''
  userForm.groupId = ''
  userForm.status = 'active'
  userForm.password = ''
  userDialogVisible.value = true
}

// 显示编辑用户对话框
const showEditUserDialog = (user) => {
  editingUserId.value = user.id
  userForm.id = user.id
  userForm.username = user.username
  userForm.phone = user.phone
  userForm.email = user.email
  userForm.groupId = user.groupId
  userForm.status = user.status
  userDialogVisible.value = true
}

// 保存用户
const handleSaveUser = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存数据
      ElMessage.success(editingUserId.value ? '用户编辑成功' : '用户新增成功')
      userDialogVisible.value = false
      fetchUsers()
    }
  })
}

// 切换用户状态
const handleToggleStatus = (user) => {
  const newStatus = user.status === 'active' ? 'inactive' : 'active'
  // 实际项目中应该调用API更新状态
  ElMessage.success(`用户已${newStatus === 'active' ? '启用' : '禁用'}`)
  fetchUsers()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  selectedGroup.value = ''
  currentPage.value = 1
  fetchUsers()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchUsers()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchUsers()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 初始化数据
fetchUsers()
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>